//
//  ConnectorViewController.m
//  CocoaSynth
//
//  Created by Thomas Dupont on 19/02/10.
//  Copyright 2010 Apple Inc. All rights reserved.
//

#import "ConnectorViewController.h"

#import "ConnectorProtocol.h"
#import "Connector.h"
#import "ConnectorView.h"
#import "PortInViewController.h"
#import "PortOutViewController.h"
#import "PortViewController.h"
#import "ConnectorLayoutViewController.h"
#import "PortIn.h"
#import "PortOut.h"
#import "Factory.h"

@implementation ConnectorViewController

@synthesize portIn;
@synthesize portOut;

- (id)initWithLayout:(ConnectorLayoutViewController*)aLayout andPortIn:(PortInViewController*)aPortIn andPortOut:(PortOutViewController*)aPortOut
{
	if (self = [super init]) {
		layout = aLayout;
		portIn = aPortIn;
		portOut = aPortOut;
		NSPoint point1 = [self pointForPort:aPortIn];
		NSPoint point2 = [self pointForPort:aPortOut];
		
		ConnectorView* connectorView = [[ConnectorView alloc] initWithFrame:NSMakeRect(0, 0, 745, 335)];
		
		[connectorView setPoint1:point1];
		[connectorView setPoint2:point2];
		self.view = connectorView;
		[self.view setNeedsDisplay:YES];
		model = [[Factory createConnector] retain];
		[model setPortIn:[portIn model]];
		[model setPortOut:[portOut model]];
		[[portIn model] setConnector:model];
		[[portOut model] setConnector:model];
	}
	return self;
}

- (void)dealloc
{
	[model release];
	[super dealloc];
}

- (void)refresh
{
	NSPoint point1 = [self pointForPort:portIn];
	NSPoint point2 = [self pointForPort:portOut];
	
	[(ConnectorView*)self.view setPoint1:point1];
	[(ConnectorView*)self.view setPoint2:point2];
	[self.view setNeedsDisplay:YES];
}

- (NSPoint)pointForPort:(PortViewController*)aPort
{
	NSPoint result;
	NSRect portFrame = [aPort view].frame;
	NSPoint portPoint;
	portPoint.x = portFrame.origin.x + portFrame.size.width / 2;
	portPoint.y = portFrame.origin.y + portFrame.size.height / 2;
	NSPoint point = [[[aPort module] view] convertPoint:portPoint toView:nil];
	result = [[layout view] convertPoint:point fromView:nil];
	return result;
}

- (BOOL)containsPort:(PortViewController*)aPort
{
	BOOL result = NO;
	if (aPort == portIn || aPort == portOut) {
		result = YES;
	}
	return result;
}

- (void)disconnect
{
	[model setPortIn:nil];
	[model setPortOut:nil];
	[[portIn model] setConnector:nil];
	[[portOut model] setConnector:nil];
}

@end
